<template>
    <div
        style="padding-top: 40px"
        v-loading="pageLoading"
        element-loading-text="正在加载,请稍等"
        element-loading-spinner="el-icon-loading"
        element-loading-background="rgba(0, 0, 0, 0.8)"
    >
        <div style="margin: 5px 10px 30px 15px">
            <!-- 1. 基础信息 -->
            <div>
                <!-- 标题 -->
                <el-row>
                    <el-col :span="12">
                        <h2 v-if="signSealStatus === 'NOIDENTITY'" style="color: red; margin-bottom: 15px">
                            您还没有实名认证，请到官网进行实名认证了在进行相应操作
                        </h2>

                        <h3 class="small-title">基础信息</h3>
                    </el-col>
                </el-row>

                <!-- 内容 -->
                <el-form :model="infoForm" style="margin-top: 15px">
                    <el-row :gutter="30">
                        <el-col :span="6">
                            <el-form-item label="转让标的名称">
                                <el-input v-model="infoForm.name" placeholder="" :disabled="isEdit"></el-input>
                            </el-form-item>
                        </el-col>

                        <el-col :span="6">
                            <el-form-item label="项目编号">
                                <el-input v-model="infoForm.number" placeholder="" :disabled="isEdit"></el-input>
                            </el-form-item>
                        </el-col>

                        <el-col :span="6">
                            <el-form-item label="转让底价">
                                <el-input v-model="infoForm.transferBasePrice" placeholder="" :disabled="isEdit"></el-input>
                            </el-form-item>
                        </el-col>
                    </el-row>
                </el-form>
            </div>

            <!-- 2. 报价方式 -->
            <div>
                <el-row>
                    <el-col :span="12">
                        <h3 class="small-title">报(竞)价方式</h3>
                    </el-col>
                </el-row>

                <el-form :model="infoForm" style="margin-top: 15px">
                    <el-row :gutter="30">
                        <el-col :span="6">
                            <el-form-item label="报价结束时间">
                                <el-input v-model="infoForm.offerEndTime" placeholder="" :disabled="isEdit"></el-input>
                            </el-form-item>
                        </el-col>
                    </el-row>

                    <el-row>
                        <el-col :span="18">
                            <el-form-item label="报价规则">
                                <el-input
                                    v-model="infoForm.offerRule"
                                    placeholder=""
                                    type="textarea"
                                    :rows="10"
                                    :disabled="isEdit"
                                ></el-input>
                            </el-form-item>
                        </el-col>
                    </el-row>

                    <el-row>
                        <el-col :span="18">
                            <el-form-item label="报价标的简介">
                                <el-input
                                    v-model="infoForm.transferBrief"
                                    placeholder=""
                                    type="textarea"
                                    :rows="10"
                                    :disabled="isEdit"
                                ></el-input>
                            </el-form-item>
                        </el-col>
                    </el-row>
                </el-form>
            </div>

            <!-- 3. 竞买登记 -->
            <div>
                <el-row>
                    <el-col :span="12">
                        <h3 class="small-title">竞买登记</h3>
                    </el-col>
                </el-row>

                <el-form :model="infoForm" style="margin-top: 15px">
                    <el-row>
                        <el-col :span="18">
                            <el-form-item label="报名方式">
                                <el-input
                                    v-model="infoForm.applyWay"
                                    placeholder=""
                                    type="textarea"
                                    :rows="10"
                                    :disabled="isEdit"
                                ></el-input>
                            </el-form-item>
                        </el-col>
                    </el-row>

                    <el-row :gutter="30">
                        <el-col :span="6">
                            <el-form-item label="看样地点">
                                <el-input v-model="infoForm.seeSite" placeholder="" :disabled="isEdit"></el-input>
                            </el-form-item>
                        </el-col>
                        <el-col :span="6">
                            <el-form-item label="看样时间">
                                <el-input v-model="infoForm.seeTime" placeholder="" :disabled="isEdit"></el-input>
                            </el-form-item>
                        </el-col>
                    </el-row>

                    <el-row>
                        <el-col :span="18">
                            <el-form-item label="保证金及处理方式">
                                <el-input
                                    v-model="infoForm.earnestMoney"
                                    placeholder=""
                                    type="textarea"
                                    :rows="10"
                                    :disabled="isEdit"
                                ></el-input>
                            </el-form-item>
                        </el-col>
                    </el-row>
                </el-form>
            </div>

            <!-- 4. 交易方式 -->
            <div>
                <el-row>
                    <el-col :span="12">
                        <h3 class="small-title">交易方式</h3>
                    </el-col>
                </el-row>

                <el-form :model="infoForm" style="margin-top: 15px">
                    <el-row :gutter="30">
                        <el-col :span="18">
                            <el-form-item label="交易地点">
                                <el-input v-model="infoForm.dealSity" placeholder="" :disabled="isEdit"></el-input>
                            </el-form-item>
                        </el-col>
                    </el-row>

                    <el-row>
                        <el-col :span="18">
                            <el-form-item label="成交确认、价款支付及合同签订">
                                <el-input v-model="infoForm.affirm" placeholder="" type="textarea" :rows="10" :disabled="isEdit"></el-input>
                            </el-form-item>
                        </el-col>
                    </el-row>

                    <el-row>
                        <el-col :span="18">
                            <el-form-item label="转让标的交割">
                                <el-input
                                    v-model="infoForm.transferDelivery"
                                    placeholder=""
                                    type="textarea"
                                    :rows="10"
                                    :disabled="isEdit"
                                ></el-input>
                            </el-form-item>
                        </el-col>
                    </el-row>

                    <el-row>
                        <el-col :span="18">
                            <el-form-item label="风险提示">
                                <el-input
                                    v-model="infoForm.riskHint"
                                    placeholder=""
                                    type="textarea"
                                    :rows="10"
                                    :disabled="isEdit"
                                ></el-input>
                            </el-form-item>
                        </el-col>
                    </el-row>

                    <el-row>
                        <el-col :span="18">
                            <el-form-item label="其他事项">
                                <el-input
                                    v-model="infoForm.otherThing"
                                    placeholder=""
                                    type="textarea"
                                    :rows="10"
                                    :disabled="isEdit"
                                ></el-input>
                            </el-form-item>
                        </el-col>
                    </el-row>

                    <el-row>
                        <el-col :span="18">
                            <el-form-item label="联系方式">
                                <el-input
                                    v-model="infoForm.contactWay"
                                    placeholder=""
                                    type="textarea"
                                    :rows="10"
                                    :disabled="isEdit"
                                ></el-input>
                            </el-form-item>
                        </el-col>
                    </el-row>

                    <el-row>
                        <el-col :span="18">
                            <el-form-item label="附件">
                                <div v-if="infoForm.attachment">
                                    <el-button type="primary" @click="downFile(infoForm.attachment)">下载查看</el-button>
                                </div>
                                <div v-else><el-button type="primary" :disabled="true">暂无附件</el-button></div>
                            </el-form-item>
                        </el-col>
                    </el-row>

                    <el-row :gutter="30">
                        <el-col :span="6">
                            <el-form-item label="中标方">
                                <el-input v-model="infoForm.companyName" placeholder="" :disabled="isEdit"></el-input>
                            </el-form-item>
                        </el-col>

                        <el-col :span="6">
                            <el-form-item label="中标金额">
                                <el-input v-model="infoForm.offer" placeholder="" :disabled="isEdit"></el-input>
                            </el-form-item>
                        </el-col>
                    </el-row>

                    <el-row :gutter="30">
                        <el-col :span="6">
                            <el-form-item label="中标时间">
                                <el-input v-model="infoForm.operateTime" placeholder="" :disabled="isEdit"></el-input>
                            </el-form-item>
                        </el-col>
                    </el-row>
                </el-form>
            </div>

            <!-- 5.操作内容 -->
            <div>
                <el-form :model="dataForm" style="margin-top: 15px">
                    <el-row :gutter="30">
                        <el-col :span="18">
                            <el-form-item label="状态">
                                <el-select v-model="baseName" placeholder="请选择" :disabled="baseNameSelectedDis">
                                    <el-option
                                        v-for="(item, index) in baseNameptions"
                                        :key="index"
                                        :label="item.baseName"
                                        :value="item.baseId"
                                    >
                                    </el-option>
                                </el-select>
                            </el-form-item>
                        </el-col>
                    </el-row>

                    <el-form-item label="上传合同">
                        <moreUpFile
                            :isShowFileList="true"
                            :isMultiple="true"
                            :upFileNum="5"
                            :isUpdisable="isUpdisable"
                            :initfileList="contractListUrl"
                            @moreUpFileSuccessHandle="SuccessHandle"
                            @moreUpFileErrorHandle="moreUpFileErrorHandle"
                            @moreUpFileHandleRemove="moreUpFileHandleRemove"
                            @moreUpFileHandleExceed="moreUpFileHandleExceed"
                        >
                        </moreUpFile>
                    </el-form-item>

                    <el-row style="margin-bottom: 60px">
                        <!-- 电子签章状态. FINISHED: 已生成,直接使用签章sealData；WAIT: 已实名认证,等待生成签章；NOIDENTITY: 未实名,请先实名认证 -->

                        <div v-if="signSealStatus === 'NOIDENTITY'">
                            <!-- <el-button type="primary" @click="goCertification()">去实名认证</el-button> -->
                        </div>

                        <div v-if="signSealStatus === 'WAIT'">
                            <el-button type="primary" @click="dataFormSubmit(1)">签字</el-button>
                        </div>

                        <div v-if="signSealStatus === 'FINISHED'">
                            <!-- <viewer :images="pageData.signSealStatus.sealData"> -->
                                <img :src="pageData.signSealStatus.sealData" class="viewer_img" />
                            <!-- </viewer> -->
                        </div>

                        <div v-if="signSealStatus === 'FINISHED' && pageData.isSign === 0 ">
                            <el-button type="primary" @click="dataFormSubmit(2)">签署合同</el-button>
                        </div>
                        <div v-if="signSealStatus === 'FINISHED' && pageData.isSign === 1 ">
                            <el-button type="primary" :disabled="true">已签署合同</el-button>
                        </div>
                    </el-row>
                </el-form>

                <span slot="footer" class="dialog-footer">
                    <el-button type="primary" @click="dataFormSubmit(3)">保存</el-button>
                    <el-button @click="closePage()">取消</el-button>
                </span>
            </div>
        </div>

        <signDialog v-if="signDialogVisible" ref="signDialogDom" @refreshDataList="getPageDeail(this.itemData.id)"></signDialog>

        <realName v-if="realNameVisible" ref="realNameDom" @refreshDataList="getPageDeail(this.itemData.id)"></realName>
    </div>
</template>
<script>
import API from '@/api';
import cloneDeep from 'lodash/cloneDeep';
import TableList from '../../../components/TableList';
import moreUpFile from '../../../components/upLoad/moreUpFile';
import signDialog from './sign-dialog';
import realName from './realName';

import { NZGMJL_RESULT_ITEMS, JDCZJL_RESULT_ITEMS, GMF_RESULT_ITEMS } from './config';

export default {
    components: {
        TableList,
        moreUpFile,
        signDialog,
        realName
    },
    data() {
        return {
            pageLoading: false,
            isEdit: true,

            //- 基础信息
            infoForm: {
                name: '', //转让标的名称
                number: '', //项目编号
                transferBasePrice: '', //转让底价

                offerEndTime: '', //报价结束时间
                offerRule: '', //报价规则
                transferBrief: '', //转让标的简介

                applyWay: '', //报名方式
                seeSite: '', //看样地点
                seeTime: '', //看样时间
                earnestMoney: '', //保证金及处理方式

                dealSity: '', //交易地点
                affirm: '', //成交确认、价款支付及合同签订
                transferDelivery: '', //转让标的交割
                riskHint: '', //风险提示
                otherThing: '', //其他事项
                contactWay: '', //联系方式

                attachment: '', //附件
                companyName: '', //中标方
                offer: '', //中标金额
                operateTime: '' //中标时间
            },

            dataForm: {
                flowStatus: '', //状态
                contract: '' //上传合同
            },
            contractList: [],
            contractListId: [],
            contractListUrl: [],

            //选择状态
            baseName: '',
            baseNameSelectedDis: false,
            baseNameptions: [
                //状态(1:进行中;2:已关闭;3:竞价成功;4:已完成;5:线下办理)
                { baseId: 1, baseName: '进行中', selected: true },
                { baseId: 2, baseName: '已关闭', selected: false },
                { baseId: 3, baseName: '竞价成功', selected: false },
                { baseId: 4, baseName: '已完成', selected: false },
                { baseId: 5, baseName: '线下办理', selected: false }
            ],

            //实名认证
            realNameVisible: false,

            //签字
            signSealStatus: '',
            signDialogVisible: false,

            //签署合同
            isUpdisable:true,

            //- 公用
            itemData: null,
            pageFlag: '',
            pageData: null
        };
    },
    mounted() {
        this.itemData = this.$route.query.itemData;
        var type = this.$route.query.type;
        if (type == 2) {
            var id = this.itemData.id;

            this.getPageDeail(id); // 获取详情信息
        }

        this.dialogType = type;
    },

    methods: {
        // 获取页面详情
        getPageDeail(id) {
            //详情
            var _that = this;

            var tick;
            let params = {
                id: id
            };

            _that.pageLoading = true;

            //详情
            API.transactionManager.getCqjyOrderDetails(params).then((res) => {
                console.log(res);

                _that.pageData = res.result;
                _that.infoForm = _that.pageData;

                //处理状态
                _that.baseName = this.pageData.flowStatus;

                //处理 签字状态
                if (_that.pageData.signSealStatus != null) {
                    _that.signSealStatus = _that.pageData.signSealStatus.status;

                    if (_that.signSealStatus === 'NOIDENTITY') {
                        _that.$message.error('您还没有实名认证，请到官网进行实名认证了在进行相应操作');
                    }

                    //已签署不能在上传 
                    if(_that.signSealStatus === 'FINISHED' && _that.pageData.isSign === 1 ){
                        _that.isUpdisable=false;
                    }


                }

                //处理 签字图片
                _that.pageData.signSealStatus.sealData='data:image/png;base64,'+_that.pageData.signSealStatus.sealData;

                //处理上传合同
                //======= 字符串，拆分id数组，拆分Url数组，拆分标识，url前缀
                if (_that.pageData.contract != null) {
                    this.disposePublicStrSplit(
                        _that.pageData.contract,
                        _that.contractList,
                        _that.contractListUrl,
                        'id',
                        '',
                        _that.contractListId
                    );
                }

                _that.pageLoading = false;
            });
        },

        disposePublicStrSplit(fileStr, splicList, splicUrlList, splicFlag, urlConnection, splicIdList) {
            //字符串，拆分id数组，拆分Url数组，拆分标识，url前缀

            if (fileStr != null && fileStr !== '') {
                //== 1.拆分字符串 ’a:b,b:a‘ 为数组
                splicList = fileStr.split(',');

                for (let index = 0; index < splicList.length; index++) {
                    //== 2.数组中的 ’a:b‘ 在拆分 为数组
                    const element = splicList[index];
                    var elmentList = element.split(':');

                    //== 3.向 上传 绑定的数据集，添加[name，url，id] 数据
                    if (elmentList.length > 0) {
                        if (splicFlag === 'url') {
                            //文件名，文件地址（url)，文件id
                            splicUrlList.push({ name: elmentList[1], url: urlConnection + elmentList[0], urlId: elmentList[0] });
                            splicIdList.push(elmentList[0]);
                        } else {
                            //文件名，文件地址(可id或url)，文件id
                            splicUrlList.push({ name: elmentList[1], url: elmentList[0], urlId: elmentList[0] });
                            splicIdList.push(elmentList[0]);
                        }
                    } else {
                        //== 3.x  做预防,有可能字符串为’a,b‘ 没有分号

                        if (splicFlag === 'url') {
                            splicUrlList.push({ name: '文件' + index, url: urlConnection + element, urlId: element });
                            splicIdList.push(element);
                        } else {
                            //文件名，文件地址(可id或url)，文件id
                            splicUrlList.push({ name: '文件' + index, url: element, urlId: element });
                            splicIdList.push(element);
                        }
                    }
                }
            }
        },

        //下载文件
        downFile(downId) {
            var reg = new RegExp('http://');

            if (reg.test(downId)) {
                var idIndex = downId.indexOf('id=');
                var idStr = downId.substring(idIndex, downId.length);

                if (idStr.indexOf('id=') != -1) {
                    window.location.href = window.baseUrl + '/sys/file/new/down?TOKEN=' + sessionStorage.getItem('token') + '&' + idStr;
                }
            } else {
                window.location.href = window.baseUrl + '/sys/file/new/down?TOKEN=' + sessionStorage.getItem('token') + '&id=' + downId;
            }
        },

        //上传合同  成功回调
        SuccessHandle([url, sigleImgId, response, file, fileList]) {
            this.diosposeJYBGFileOp([file, fileList]);
        },

        //检验报告 上传文件 删除回调
        moreUpFileHandleRemove([file, fileList]) {
            this.diosposeJYBGFileOp([file, fileList]);
        },

        diosposeJYBGFileOp([file, fileList]) {
            this.contractList = [];

            for (let index = 0; index < fileList.length; index++) {
                const element = fileList[index];
                console.log('合同文件上传回调：', element);

                if (element.response != null) {
                    //不等于空为刚上传的文件
                    this.contractList.push(element.response.result[0] + ':' + element.name);
                    this.contractListId.push(element.response.result[0]);
                } else {
                    //为空为之前上传的文件
                    this.contractList.push(element.urlId + ':' + element.name);
                    this.contractListId.push(element.urlId);
                }
            }
        },

        //上传合同 失败回调
        moreUpFileErrorHandle(val) {
            this.$message.error(`文件上传失败`);
        },

        //上传合同 多文件上传，超出限制回调
        moreUpFileHandleExceed([files, fileList]) {
            this.$message.warning(
                `当前限制选择 5 个文件，本次选择了 ${files.length} 个文件，共选择了 ${files.length + fileList.length} 个文件`
            );
        },

        //获取选择状态
        getBaseNameptions(parm, name) {
            if (this.isChinese(name)) {
                //全是中文，代表用户没有选择，为默认值，或者
                for (var i = 0; i < this.baseNameptions.length; i++) {
                    if (this.baseNameptions[i].baseName === name) {
                        this.dataForm.flowStatus = this.baseNameptions[i].baseId;
                        parm.flowStatus = this.baseNameptions[i].baseId;
                    }
                }
            } else {
                //选择之后，name为代码id
                for (var i = 0; i < this.baseNameptions.length; i++) {
                    if (this.baseNameptions[i].baseId === name) {
                        this.dataForm.flowStatus = this.baseNameptions[i].baseId;
                        parm.flowStatus = this.baseNameptions[i].baseId;
                    }
                }
            }
        },

        //是否全是 中文
        isChinese(temp) {
            var re = /[^\u4e00-\u9fa5]/;
            if (re.test(temp)) return false;
            return true;
        },

        //去实名认证
        goCertification() {
            this.realNameVisible = true;
            var userType = sessionStorage.getItem('userType');
            console.log('获取的用户类型：', userType);

            // this.$refs.realNameDom.init(userType);
            this.$refs.realNameDom.init('CORP');
        },

        //用户操作 ： 签字， 签署合同 ，保存
        dataFormSubmit(type) {
            if (type == 1) {
                //签字
                this.signDialogVisible = true;
                var userType = sessionStorage.getItem('userType');
                console.log('获取的用户类型：', userType);
                this.$refs.signDialogDom.init(userType);
            }

            if (type == 2) {
                //签署合同

                let params = {
                    biddingId: this.pageData.biddingId, //竞价实例id
                    id: this.pageData.id //订单id
                };

                //合同 处理
               
                if (this.contractList.length == 0&& this.contractListUrl.length == 0) {
                    this.$message.error('请上传合同');
                    return;
                }

                params.contract = this.contractListId[0];
                API.transactionManager.getCqjyOrderDetails_SignContract(params).then((data) => {
                    if (data.code == '0000') {
                        this.$message({
                            message: '操作成功',
                            type: 'success',
                            duration: 1500,
                            onClose: () => {
                              this.contractList=[];
                              this.contractListUrl=[];
                              this.getPageDeail(this.itemData.id);
                            }
                        });
                    }
                });


            }

            if (type == 3) {
                //保存
                let params = {
                    biddingId: this.pageData.biddingId, //竞价实例id
                    id: this.pageData.id //订单id
                };

                //选择状态 处理
                this.getBaseNameptions(params, this.baseName);

                //合同 处理
                if (this.contractList.length == 0&& this.contractListUrl.length == 0) {
                    this.$message.error('请上传合同');
                    return;
                }

                //合同 上传处理
                if (this.contractList.length > 0) {
                    this.dataForm.contract = this.contractList.join(',');
                    params.contract = this.dataForm.contract;
                }

               
                API.transactionManager.getCqjyOrderDetails_Save(params).then((data) => {
                    if (data.code == '0000') {
                        this.$message({
                            message: '操作成功',
                            type: 'success',
                            duration: 1500,
                            onClose: () => {
                                this.closePage();
                            }
                        });
                    }
                });
            }
        },

        closePage() {
            this.$router.go(-1);
        }
    }
};
</script>
<style scoped>
.viewer_img {
    position: relative;
    width: 100px;
    height: 100px;
}
</style>